package br.ufpe.cin.tose.copapolling;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import br.ufpe.cin.tose.copapolling.models.Jogo;
import br.ufpe.cin.tose.copapolling.models.Time;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private static final String TAG = "MainActivity";
	public static final String URLTimes = "http://www.cin.ufpe.br/~salc/times";
	public static final String URLJogos = "http://www.cin.ufpe.br/~salc/jogos";
	int indiceJogos = 0;
	int indexSharedPreferencesTimes = 0;
	int indexSharedPreferencesJogos = 0;

	public static MainActivity mainActivity;

	TextView tvNomeTime1, tvNomeTime2, tvLocalJogo;
	ImageView ivFotoTime1, ivFotoTime2;
	ImageView ivPlacarTime1, ivPlacarTime2;

	ListView list;
	LazyAdapter adapter;

	ArrayList<Jogo> jogosList;

	ArrayList<Time> times;
	
	
	
	
	private PendingIntent pendingIntent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mainActivity = this;

		tvNomeTime1 = (TextView) findViewById(R.id.nomeTime1);
		tvNomeTime2 = (TextView) findViewById(R.id.nomeTime2);
		tvLocalJogo = (TextView) findViewById(R.id.localJogo);
		ivFotoTime1 = (ImageView) findViewById(R.id.fotoTime1);
		ivFotoTime2 = (ImageView) findViewById(R.id.fotoTime2);
		ivPlacarTime1 = (ImageView) findViewById(R.id.placarTime1);
		ivPlacarTime2 = (ImageView) findViewById(R.id.placarTime2);

		list = (ListView) findViewById(R.id.list);

		// Intent intent = new Intent(getApplicationContext(),
		// AtualizaService.class);
		// startService(intent);

		// registerReceiver(receiver, new
		// IntentFilter(AtualizaService.NOTIFICATION));


		/*
		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor keyValuesEditor = keyValues.edit();
		indiceJogos = keyValues.getInt("indiceJogos", 0);

		apagaSharedPreferences();
		
		if (indiceJogos == 150){	indiceJogos = 1;}
		GetHTML request = new GetHTML();
		request.execute(URLTimes,URLJogos + indiceJogos);
		indiceJogos++;
		
		keyValuesEditor.putInt("indiceJogos", indiceJogos);
		keyValuesEditor.commit();
		*/
		
		createNotification();
		
		Intent it = new Intent(MainActivity.mainActivity.getApplicationContext(), AtualizaService.class);
		MainActivity.mainActivity.startService(it);

	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.d("serviceatualiza", "entrou onreceive main");
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				String result = bundle.getString("msg");

				resgataTimes();
				resgataJogos();

				atualizaViewJogos();
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, new IntentFilter(
				AtualizaService.NOTIFICATION));
	}

	protected void onPause() {
		super.onPause();
		// unregisterReceiver(receiver);
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		return false;
	}

	public void apagaSharedPreferences() {
		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		keyValues.edit().clear().commit();
	}

	public void resgataTimes() {
		if (times == null) {
			times = new ArrayList<Time>();
		}

		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		int indexSharedPreferencesTimes = keyValues.getInt("indextimes", 0);

		for (int j = 0; j <= indexSharedPreferencesTimes; j++) {
			String msg = keyValues.getString("t" + j, null);
			if (msg != null) {
				String[] msgDividida = msg.split("#");
				Time time = new Time();

				time.setId(Integer.parseInt(msgDividida[0])); // Porque o
																// primeiro
																// elemento é o
																// indicador se
																// é tiem ou
																// jogo
				time.setNome(msgDividida[1]);
				time.setUrlBandeira(msgDividida[2]);

				times.add(time);
			}
		}

	}

	public void resgataJogos() {
		ArrayList<Jogo> jogos = new ArrayList<Jogo>();

		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		int indexSharedPreferencesJogos = keyValues.getInt("indexjogos", 0);

		for (int j = 0; j <= indexSharedPreferencesJogos; j++) {
			String msg = keyValues.getString("j" + j, null);
			if (msg != null) {
				String[] msgDividida = msg.split("#");
				Jogo jogo = new Jogo();

				jogo.setIdTime1(Integer.parseInt(msgDividida[0]));
				jogo.setIdTime2(Integer.parseInt(msgDividida[1]));
				jogo.setLocalJogo(msgDividida[2]);
				int[] placar = { Integer.parseInt(msgDividida[3]),
						Integer.parseInt(msgDividida[4]) };
				jogo.setPlacar(placar);

				jogos.add(jogo);
			}
		}
		this.jogosList = jogos;

	}

	public void atualizaViewJogos() {
		resgataTimes();
		resgataJogos();
		ArrayList<HashMap<String, String>> maps = new ArrayList<HashMap<String, String>>();
		if (jogosList != null && jogosList.size() > 0 && times != null
				&& times.size() > 0) {
			for (int i = 0; i < jogosList.size(); i++) {
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("NomeTime1", times.get(jogosList.get(i).getIdTime1())
						.getNome() + ""); // Pegar o nome do time
				map.put("NomeTime2", times.get(jogosList.get(i).getIdTime2())
						.getNome() + "");
				map.put("LocalJogo", jogosList.get(i).getLocalJogo());
				map.put("GolsTime1", jogosList.get(i).getPlacar()[0] + "");
				map.put("GolsTime2", jogosList.get(i).getPlacar()[1] + "");
				maps.add(map);
			}
			if (maps.size() != 0) {
				adapter = new LazyAdapter(this, maps);
				list.setAdapter(adapter);
			}
		}
	}

	private void createNotification() {
		Intent intent = new Intent(this.getApplicationContext(),
				MainActivity.class);
		PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
				0, intent, 0);

		final Notification notification = new Notification.Builder(
				getApplicationContext())
				.setContentTitle(getResources().getString(R.string.app_name))
				.setContentText("Executando... Clique para abrir")
				.setSmallIcon(R.drawable.ic_launcher).setContentIntent(pi)
				.build();
		notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
		notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;

		final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.notify(R.string.app_name, notification);
	}

	public void saveArrayTimes(String msg) {
		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor keyValuesEditor = keyValues.edit();
		indexSharedPreferencesTimes = keyValues.getInt("indextimes", 0);
		keyValuesEditor.putString("t" + indexSharedPreferencesTimes, msg);
		keyValuesEditor.commit();
		indexSharedPreferencesTimes++;
		keyValuesEditor.putInt("indextimes", indexSharedPreferencesTimes);
		keyValuesEditor.commit();
	}

	public void saveArrayJogos(String msg) {
		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor keyValuesEditor = keyValues.edit();

		indexSharedPreferencesJogos = keyValues.getInt("indexjogos", 0);

		keyValuesEditor.putString("j" + indexSharedPreferencesJogos, msg);
		keyValuesEditor.commit();

		indexSharedPreferencesJogos++;
		keyValuesEditor.putInt("indexjogos", indexSharedPreferencesJogos);
		keyValuesEditor.commit();
	}

	public void retornoDoWork(String times, String jogos) {
		if (times != null) {
			// ID#NomeTime#URLBandeira
			String[] timesN = times.split("@");
			for (String time : timesN) {
				saveArrayTimes(time);
			}
		}
		String[] jogosN = jogos.split("@");
		for (String jogo : jogosN) {
			saveArrayJogos(jogo);
		}
		atualizaViewJogos();
	}

	public void repete() {
		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor keyValuesEditor = keyValues.edit();
		indiceJogos = keyValues.getInt("indiceJogos", 0);

		apagaSharedPreferences();
		
		if (indiceJogos == 150){	indiceJogos = 1;}
		GetHTML request = new GetHTML();
		request.execute(URLTimes,URLJogos + indiceJogos);
		indiceJogos++;
		
		keyValuesEditor.putInt("indiceJogos", indiceJogos);
		keyValuesEditor.commit();
	}

}
